<template> 
  <div class="app-container">
    <header-search class="g-w100 g-h100 colon mainSearchPanel">
      <el-row>
        <el-col :span="24" style="text-align: left">
          <p class="page-header-title">
            <i class="el-icon-right"></i>
            {{title}}
          </p>
        </el-col>
      </el-row>
    </header-search>

    <page-panel-new class="mainListPanel"  :header-title="title">
      <el-row class="mbBottom">
        <el-col :span="16">
          <el-button type="primary" @click="doAdd"> 新增 </el-button>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button type="primary" @click="doExportExcel"> 导出 </el-button>
        </el-col>
      </el-row>
      <el-table ref="table-main" :data="data" :height="tableHeight" :row-style="{ height: '0px' }"
        :header-cell-style="{ 'text-align': 'center', padding: '0px 0' }" header-cell-class-name="table_header"
        highlight-current-row
        :cell-style="{ padding: '2px', 'text-align': 'center' }" style="width: 100%; height: 100%">
        <el-table-column label="序号" align="right" prop="id" width="50">
          <template slot-scope="scope">
            {{ scope.$index + (queryParams.pageSize * (queryParams.pageNum-1)) + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="调查内容" align="left" prop="dcnr" width="200" show-overflow-tooltip />
        <el-table-column label="满意度" align="left" prop="myd" width="150" show-overflow-tooltip />
        <el-table-column label="日期" align="left" prop="rq" width="200" show-overflow-tooltip />
        <el-table-column label="意见" align="left" prop="yj" width="400" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="delbutton" @click="doUpdate(scope.row, scope.$index)"> 修改 </el-button>
            <el-button type="text" class="delbutton" @click="doDelete(scope.row, scope.$index)"> 删除 </el-button>
            <el-button type="text" @click="doView(scope.row, scope.$index)"> 查看 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="pagination.total" class="mainListPagination" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getListData" />
    </page-panel-new>


    <el-dialog :title="dialogTitle" :visible.sync="OpType.Open" width="900px" append-to-body>
      <div class="el-dialog-div">
        <el-form ref="form-main" :model="formData" :rules="rules" :validate-on-rule-change=false label-width="120px" :disabled="formDisable">
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="调查内容" prop="dcnr">
                <!--visible-change、clear这两个事件主要处理 select失去焦点校验bug-->
                <el-select filterable clearable :placeholder="showPlaceHolder?'请选择':''" v-model="formData.dcnr" style="width: 300px"
                  @visible-change="handleSelectVisibleChange($event, 'dcnr')" @clear="handleSelectClear('dcnr')"> 
                  <el-option
                    v-for="({sjxdm, sjxmc}) in selectorData_in_dcnr"
                    :key="sjxdm"
                    :label="sjxmc"
                    :value="sjxdm">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="满意度" prop="myd">
                <!--visible-change、clear这两个事件主要处理 select失去焦点校验bug-->
                <el-select filterable clearable :placeholder="showPlaceHolder?'请选择':''" v-model="formData.myd" style="width: 300px"
                  @visible-change="handleSelectVisibleChange($event, 'myd')" @clear="handleSelectClear('myd')"> 
                  <el-option
                    v-for="({sjxdm, sjxmc}) in selectorData_in_myd"
                    :key="sjxdm"
                    :label="sjxmc"
                    :value="sjxdm">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="意见" prop="yj" >
                <el-input v-model="formData.yj" :placeholder="showPlaceHolder?'请输入':''" type="textarea" :rows="15"  style="width: 700px"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="!formDisable" type="primary" @click="doSubmit"> 保存 </el-button>
        <el-button class="cancelBtn" @click="doClose"> 关 闭 </el-button>
      </div>
    </el-dialog>


  </div>

</template>
<script lang="ts">
import Vue from 'vue'
import Trend from '@/components/mainEntrance/trend/index.vue'
import { prefix } from '@/config/global'
import {
  getListData,
  getSelectorData,
  submit,
  submit_delete,
  exportExcel,
} from '@/api/syfxxtApi/khfw/myddc/api.js'
import {
  CONTRACT_STATUS,
  CONTRACT_STATUS_OPTIONS,
  CONTRACT_TYPES,
  CONTRACT_PAYMENT_TYPES,
} from '@/constants'
import dayjs from 'dayjs'


const FORM_INITIALDATA = { //录入Form初始化数据
      __rowindex:'',
      optype:'',
      id: '', 
      khdw: '', 
      dcnr: '', 
      myd: '', 
      rq: '', 
      yj: '', 
      s_cjr: '', 
      s_cjsj: '',
    };

const QUERY_PARAMS_INITIALDATA = { //查询参数初始化数据
    pageNum: 1,
    pageSize: 20,
  };


export default Vue.extend({
  name: 'Khfw-Myddc',
  data() {
    return {
      title: '满意度调查',
      dialogTitle: '',
      thCss: 'custom-th-class',
      tableHeight: window.innerHeight - 320,
      CONTRACT_STATUS,
      CONTRACT_STATUS_OPTIONS,
      CONTRACT_TYPES,
      CONTRACT_PAYMENT_TYPES,
      prefix,
      dataLoading: false,
      data: [], //主表格数据
      selectorData_in_dcnr: [], //录入选择器 下拉数据
      selectorData_in_myd: [], //录入选择器 下拉数据
      OpType: {
        Open: false,
        Delete: false,
        OpenFJ: false,
        Export: false,
      },
      selectedRowKeys: [],
      value: 'first',
      formData: { ...FORM_INITIALDATA }, //录入Form数据
      formDisable: false, 
      showPlaceHolder: true, 
      queryParams: {...QUERY_PARAMS_INITIALDATA}, //查询参数
      rules: { //录入验证规则
        dcnr: [{ required: true, message: "请选择。", trigger: "blur" }],
        myd: [{ required: true, message: "请选择。", trigger: "blur" }],
      },
      rowKey: 'id',
      tableLayout: 'fixed',
      verticalAlign: 'top',
      hover: true,
      pagination: { //翻页配置
        defaultPageSize: 20,
        total: 0,
        defaultCurrent: 1,
      },
      upload: {  //上传配置
        uploadVisible: false, //上传项是否显示，在查看时不显示
        uploadFiles: [], //已上传文件列表
      },
      exportVisible: false,
      imgSrc: ''
    }
  },
  computed: {

  },
  mounted() {
    this.getSelectorData_in_dcnr();
    this.getSelectorData_in_myd();
    this.getListData();
    this.doLayout();
  },
  methods: {
    // 布局计算
    doLayout() {
      this.$nextTick(()=>{
        var winHeight = 0;
        if (window.innerHeight) {
            winHeight = window.innerHeight;
        } else if (document.body && document.body.clientHeight) {
            winHeight = document.body.clientHeight;
        } 
        else if (document.documentElement && document.documentElement.clientHeight) {
            winHeight = document.documentElement.clientHeight;
        }
        
        var queryPanelHeight = this.$el.querySelector('.mainSearchPanel').offsetHeight;
        var mainPanelHeight = winHeight - queryPanelHeight - 150;
        var paginationHeight = this.$el.querySelector('.mainListPagination').offsetHeight;
        this.$el.querySelector('.mainListPanel').style.height = mainPanelHeight+ 'px';
        this.tableHeight = mainPanelHeight - 130;
      })
    },
    //获取主表格查询数据
    getListData() {
      try {
        this.dataLoading = true  
        const param = {
          start: (this.queryParams.pageNum - 1) * this.queryParams.pageSize,
          limit: this.queryParams.pageSize,
        };
        getListData(param).then((res) => {
          if (res.success) {
            this.data = res.rows;
            this.pagination.total = res.total;
            this.exportDisabled = this.data.length == 0;
            this.queryParams.commitedParam = param;
          } else {
            this.data = []
            this.$message.error({ content: '请重新搜索!', placement: 'center' })
          }
          this.doLayout();
        })
      } catch (error) {
        this.dataLoading = false;
        console.warn('接口提示', error);
        this.doLayout();
      }
    },
    //获取 选择器数据
    getSelectorData_in_dcnr() {
      try {
        const param = {
        };
        getSelectorData("in_dcnr", param).then((res) => {
          if (res.success) {
            this.selectorData_in_dcnr = res.rows;
          } else {
            this.selectorData_in_dcnr = [];
          }
        })
      } catch (error) {
        console.warn('接口提示', error)
      }
    },
    // 获取选择器数据
    getSelectorData_in_myd() {
      try {
        const param = {
        };
        getSelectorData("in_myd", param).then((res) => {
          if (res.success) {
            this.selectorData_in_myd = res.rows;
          } else {
            this.selectorData_in_myd = [];
          }
        })
      } catch (error) {
        console.warn('接口提示', error)
      }
    },
    //处理新增按钮事件
    doAdd() {
      this.OpType.Open = true;
      this.$nextTick(()=>{
        this.formDisable = false;
        this.showPlaceHolder = true;
        this.formData = { ...FORM_INITIALDATA };
        this.formData.optype = 'add';
        this.dialogTitle = this.title + ' >> 新增';
      });
    },
    //处理修改按钮事件
    doUpdate(row, rowindex) {
      this.OpType.Open = true;
      
      this.$nextTick(()=>{
        this.formDisable = false;
        this.showPlaceHolder = true;
        this.$refs['table-main'].setCurrentRow(row);
        this.formData = {...row};
        this.formData.optype = 'update';
        this.formData.__rowindex = rowindex;
        this.dialogTitle = this.title + ' >> 修改';
      
      });
    },
    //处理删除按钮事件
    doDelete(row, rowindex) {
      return this.$modal.confirm("是否确认删除该条数据？")
      .then(() => {
        submit_delete({ id: row.id })
          .then((res) => {
            if (res.success) {
              this.data.splice(rowindex, 1);
              this.$message.success({ content: '删除成功!', placement: 'center' })
            } else {
              this.$message.error({ content: '删除失败!', placement: 'center' })
            }
          })
          .catch(() => { 
            this.$message.error({ content: '删除失败!', placement: 'center' })
          });
      })
      .catch(() => { 
      });
    },
    //处理查看按钮事件
    doView(row, rowindex) {
      this.OpType.Open = true;
      this.$nextTick(()=>{
        this.formDisable = true;
        this.showPlaceHolder = false;
        this.$refs['table-main'].setCurrentRow(row);
        this.formData = {...row};
        this.formData.__rowindex = rowindex;
        this.dialogTitle = this.title + ' >> 查看';
      });
    },
    //处理导出按钮事件
    doExportExcel() {
      var params = {...this.queryParams.commitedParam};
      for (let key in params) {
        if (/^sel_/.test(key)) {
          var new_key = key.replace(/^sel_/, 'p_');
          params[new_key] = params[key];
        }
      }
      try {
        if (!this.queryParams.commitedParam) {
          this.$message.info({ content: '请先查询数据!', placement: 'center' })
        }
        const filename = this.title + '-' + dayjs().format('YYYYMMDDHHmmssSSS') + '.xls';
        exportExcel(this.download, params, filename);
      } catch (error) {
      }
    },
    //处理下载附件按钮事件
    doDownloadFile(param) {
    },
    //处理保存按钮事件
    doSubmit() {
      this.$refs['form-main'].validate((valid) => {
        if (valid) {
          var _data = {...this.formData};

          var _submitData = new FormData();
          for (let key in _data) {
            if (_data[key] && _data[key] instanceof Date) {
              _data[key] = dayjs(_data[key]).format('YYYY-MM-DD');
            }
            _submitData.append(key, _data[key]);
          }     
          submit(_submitData)
          .then((res) => {
            if (res.success) {
              if (this.formData.optype == 'add') {
                _data.id = res.id;
                _data.rq = res.extraData.rq;
                this.data.unshift(_data);
                this.$refs['table-main'].setCurrentRow(this.data[0]);
              } else {
                _data.rq = res.extraData.rq;
                this.data.splice(_data.__rowindex, 1, _data);
              }
              this.OpType.AddOrUpdate = false;
              this.$message.success({ content: '保存成功!', placement: 'center' })
              this.OpType.Open = false;
            } else {
              this.$message.error({ content: '保存失败!', placement: 'center' })
            }
          })
          .catch(() => { 
            this.$message.error({ content: '保存失败!', placement: 'center' })
          });
        }
      });
    },
    //处理关闭事件
    doClose() {
      this.OpType.Open = false;
    },
    //处理查看附件按钮关闭事件
    doCloseFJ() {
    },
    //查询参数重置按钮事件
    resetQuery() {
      this.queryParams = {...QUERY_PARAMS_INITIALDATA};
    },
    //翻页事件
    handlePageChange(pageInfo) {
      this.getListData()
      // this.pagination.defaultCurrent = pageInfo.current;
    },
    //查询参数获得日期改变事件
    onQueryParamChange_hdrq(val) {
    },
    //查询参数知识产权类别改变事件
    onQueryParamChange_zscqlb(val) {
    },
    //录入Select下拉列表显示改变事件
    handleSelectVisibleChange(e, r) {
      this.$refs['form-main'].validateField(r);
    },
    //录入Select清除事件
    handleSelectClear(r) {
      this.$refs['form-main'].validateField(r);
    },
    //上传文件改变事件
    handleUploadChange(file, filelist) {
    },
    //上传文件删除前事件
    handleUploadBeforeRemove(file, filelist) {
    },
    //上传文件删除事件
    handleUploadRemove(file, filelist) {
    },
    test() {
      alert(1);
    }
      
  },
})
</script>
<style lang="less" scoped>
.app-container {
  height: 100%;

  .el-table {
    overflow: scroll;
  }
}

::v-deep .el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

/deep/ .is-left > div {
    text-align: left;
}

/deep/ .is-right > div {
    text-align: right;
}

/deep/ .is-left > div {
    text-align: left;
}

/deep/ .is-center > div {
    text-align: center;
}

::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner,
::v-deep .el-radio.is-disabled .el-radio__inner,
::v-deep .el-radio.is-disabled .el-radio__label,
::v-deep .el-checkbox.is-disabled .el-checkbox__inner,
::v-deep .el-checkbox.is-disabled .el-checkbox__label {
  background-color: #f6f6f6 !important; /* 示例：改变背景颜色 */
  color: #333 !important; /* 示例：改变文字颜色 */
}

::v-deep .el-upload.el-upload--text {
  margin :0 !important;
}

.mainSearchPanel .page-header-title {
  font-size:16px;
  color: #409EFF;
  font-weight: bolder;
  display: block;
  margin:0;
  padding:0;
  margin:10px 0;
}

.mainSearchPanel .el-divider--horizontal {
  margin:0 !important;
  margin-top:10px;
}

</style>
